<?php

namespace app\common\service\auth;

use app\common\facade\auth\Auth;
use app\model\Admin;
use app\model\AdminPermission;
use app\model\AdminRole;
use think\Exception;
use think\facade\Db;

class AuthAdminService extends AuthBase implements AuthInterface
{
    /**
     * @var Admin
     */
    public $admin;

    public function attempt($params)
    {

        if ('local' == config('app.app_env')) {
            return $this->admin = Admin::query()
                ->where('id', 1)
                ->where('is_deleted', 0)
                ->find();
        }

        $accessToken = request()->header('Authorization');

        if (empty($accessToken)) {
            return false;
        }

        //是数组
        $adminInfo = cache($accessToken);

        if (empty($adminInfo)) {
            return false;
        }


        $auth = new \app\admin\model\Auth();
        $auth->refreshToken($adminInfo['refresh_token']);

        $this->admin = Admin::query()
            ->where('id', $adminInfo['admin_id'] ?? 0)
            ->where('is_deleted', 0)
            ->find();

        if (empty($this->admin)) return false;


        if (1 != $this->admin->status) {
            return false;
        }

        if (\app\model\AdminPermission::query()->whereExists(['type' =>\app\model\AdminPermission::TYPE_API,'url' => request()->pathinfo()])){
            //查看是否有权限
            if (!collect(Auth::permissions())->where('type',\app\model\AdminPermission::TYPE_API)->where('url',request()->pathinfo())){
                throw new Exception('无权限操作');
            }
        }


        return $this->admin;

    }

    public function login($params)
    {
        //todo...
    }

    public function id()
    {
        return $this->admin->id;
    }

    /**
     * @return Admin
     */
    public function user()
    {
        return $this->admin;
    }


    /**
     * 获取所有权限
     */
    public function permissions()
    {

        if ($this->id() == 1) { //超管
            return AdminPermission::query()->select();
        }
        /**
         * @var AdminRole $role
         */
        $role = AdminRole::query()
            ->where('id', $this->id())
            ->find();
        if (empty($role)){
            return  [];
        }
        if (empty($role->permissions)){
            return [];
        }

        return $role->permissions;

    }


}